package com.xnx.bincker.leader.core.repository;

import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;

/**
 * repository工厂类
 */
public class RepositoryFactoryBean<T extends BasicRepository<S, ID>, S, ID> extends JpaRepositoryFactoryBean<T, S, ID> {
	public RepositoryFactoryBean(Class<? extends T> repositoryInterface) {
		super(repositoryInterface);
	}

	@Override
	protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
		return new BasicRepositoryFactory<S, ID>(entityManager);
	}

	private static class BasicRepositoryFactory<S, ID> extends JpaRepositoryFactory {
		private EntityManager entityManager;

		@Override
		protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
			return BasicRepositoryImpl.class;
		}

		@Override
		protected Object getTargetRepository(RepositoryInformation information) {
			return new BasicRepositoryImpl<S, ID>((Class<S>) information.getDomainType(), entityManager);
		}

		BasicRepositoryFactory(EntityManager entityManager) {
			super(entityManager);
			this.entityManager = entityManager;
		}
	}
}
